package com.spring.redis.operation.service.base.impl;


import com.spring.redis.operation.service.base.RedisBaseService;
import com.spring.redis.operation.utils.RedisOperationUtils;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * redis Operation base class
 *
 * @author zhouyu
 * @date 2020年04月12日14:33:38
 */
@Service
@AllArgsConstructor
public class RedisBaseServiceImpl implements RedisBaseService {

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 删除key
     *
     * @param keys keys
     */
    @Override
    public void del(@NonNull String... keys) {
        redisTemplate.delete(RedisOperationUtils.arrToSet(keys));
    }

    /**
     * 设置key的过期时间
     *
     * @param key     key
     * @param seconds 过期时间，单位秒
     */
    @Override
    public void expire(@NonNull String key, @NonNull Long seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    /**
     * 设置key的过期时间
     *
     * @param key      key
     * @param expire   自定义过期时间
     * @param timeUnit 自定义时间类型,为null默认单位为秒
     */
    @Override
    public void expire(@NonNull String key, @NonNull Long expire, TimeUnit timeUnit) {
        redisTemplate.expire(key, expire, timeUnit == null ? TimeUnit.SECONDS : timeUnit);
    }

    /**
     * 判断key是否存在
     *
     * @param key key
     * @return java.lang.Boolean
     */
    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}
